<template>
  <div class="layout-padding">
    <div class="layout-padding-auto layout-padding-view">
      <avue-crud 
        ref="crud" 
        v-model="form" 
        v-model:search="searchForm"
        :page="page" 
        :data="tableData" 
        :table-loading="tableLoading"
        :option="tableOption" 
        :before-open="handleOpenBefore" 
        @on-load="getList"
        @search-change="searchChange"
        @search-reset="resetsearch" 
        @refresh-change="refreshChange" 
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-del="rowDel"
        @selection-change="handleSelectionChange">
        <template #menu="{row}">
          <el-button v-if="row.alarmStatus != '1'" class="filter-item" type="text" v-auth="'alarm_alarmRecord_del'"  icon="setting" @click="confirmStatus(row)">确认</el-button>
        </template>
        <template #menu-left="{}">
          <el-button class="filter-item" type="primary" v-auth="'alarm_alarmRecord_del'" :disabled="multiple" icon="delete" @click="handleDelete(selectObjs)">删除 </el-button>
        </template>
        <template #menu-right="{}">
          <el-button class="filter-item"  v-auth="'alarm_alarmRecord_export'" circle icon="Download"  @click="exportExcel"></el-button>
        </template>
        <template #alarmTypeName-search>
          <el-select v-model="searchForm.alarmTypeCode" placeholder="请选择告警类型">
            <el-option v-for="(item, index) in alarmTypeData" :key="index" :label="item.typeName" :value="item.typeCode"></el-option>
          </el-select>
        </template>
        <template #happenTime-search>
          <el-date-picker
            v-model="query.queryTime"
            type="datetimerange"
            range-separator="-"
            format="YYYY-MM-DD HH:mm:ss"
            valueFormat="YYYY-MM-DD HH:mm:ss"
            start-placeholder="起始时间"
            end-placeholder="结束时间"
          />
        </template>
      </avue-crud>
    </div>
  </div>
</template>

<script lang="ts" name="alarmSetting" setup>
import { fetchList, addObj, putObj, getObj, delObjs } from '/@/api/alarm/alarminfo'
import { fetchList as  fetchAlarmTypeData} from '/@/api/alarm/alarmsetting'
import { tableOption } from '/@/crud/alarm/alarminfo';


import { validateNull } from '/@/utils/validate';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { useDict } from '/@/hooks/dict';
import other from '/@/utils/other';

const { alarm_way, alarm_level } = useDict('alarm_way', 'alarm_level');

let date = new Date().toJSON().split('T')[0]

let query:any = ref({
  // queryTime: [date + ' 00:00:00', date + ' 23:59:59'],
  alarmStatus: '0'
})

const form:any = ref({})
const searchForm: any = ref({
  alarmStatus: '0'
})
const tableLoading = ref(false)
const multiple = ref(true);
const selectObjs = ref([]) as any;
const page:any = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10, // 每页显示多少条
})
let tableData = ref([])
let alarmTypeData:any = ref([])

onMounted(() => {
  fetchAlarmTypeData({ current: 1,size: 9999,}).then(res => {
    alarmTypeData.value = res.data.records || []
  })
})

//初始化获取数据
const getList = (page: any, params?: object) => {
  tableLoading.value = true;
  fetchList(
    Object.assign(
      {
        current: page.currentPage,
        size: page.pageSize
      },
      query.value,
      params
    )
  )
    .then((res) => {
      tableLoading.value = false;
      tableData.value = res.data.records || []
      page.total = res.data.total
    })
    .catch(() => {
      tableLoading.value = false;
    });
}

//打开弹框
const handleOpenBefore = (show: Function, type: string) => {
  show();
}
// 多选事件
const handleSelectionChange = (objs: { id: string }[]) => {
  selectObjs.value = objs.map(({id}) => id);
  multiple.value = !objs.length;
};

//批量删除
const handleDelete = (selectObjs:Array<string>) => {
  useMessageBox().confirm('是否确认批量删除？').then(() => {
    delObjs(selectObjs).then(() => {
      useMessage().success('删除成功');
      getList(page);
    })
    .catch((err: any) => {
      useMessage().error(err.msg);
    });
  });
}
//单条删除
const rowDel = (row:any, index:number) => {
  useMessageBox().confirm('是否确认删除告警类型为' + row.alarmTypeName).then(() => {
    delObjs([row.id]).then(() => {
      useMessage().success('删除成功');
      getList(page);
    })
    .catch((err: any) => {
      useMessage().error(err.msg);
    });
  });
}
const confirmStatus = (row: any) => {
  useMessageBox().confirm('是否确认此条报警信息？').then(() => {
    row.alarmStatus = '1'
    putObj(row).then(() => {
      useMessage().success('确认成功');
      getList(page);
    })
    .catch((err: any) => {
      useMessage().error(err.msg);
    });
  });
}
const sizeChange = (pageSize:number) => {
  page.pageSize = pageSize;
}
const currentChange = (current:number) => {
  page.currentPage = current;
}
const searchChange = (form:any, done:Function) => {
  page.currentPage = 1;
  page.pageSize = 10
  form.alarmTypeCode = searchForm.value.alarmTypeCode
  getList(page, form);
  done();
}
const refreshChange = () => {
  getList(page);
}
const resetsearch = () =>{
  searchForm.value.typeCode = ''

}
const exportExcel = () => {
  other.downBlobFile('/admin/accessSubarea/export', {}, '告警信息记录列表.xlsx');
}
watch(
    () => searchForm.value.alarmStatus,
    (val) => {
      if(validateNull(val)){
        query.value.alarmStatus = ''
      }
      
    }
);
</script>
<style lang="scss" scoped>
:deep(.el-date-editor.el-input__wrapper){
  width: 100%;
}

</style>
